package com.bus.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bus.entity.Categorys;
import com.bus.entity.Products;
import com.bus.entity.Providers;
import com.bus.exception.MyException;
import com.bus.service.CategoryService;
import com.bus.service.ProductService;
import com.bus.service.ProviderService;
import com.bus.util.BootStrapPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;

//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;

@Controller
public class ProductController {
	@Autowired
	private ProductService ps;

	@Autowired
	private ProviderService pros;

	@Autowired
	private CategoryService cs;

	@RequestMapping(value = "/getBoth.action", method = RequestMethod.GET, produces = "text/json;charset=utf-8")
	public void getBoth(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Providers> list1 = pros.findAllProvider();
		List<Categorys> list2 = cs.findAllCategory();
		// System.out.println(list1);
		Object[] arr = { list1, list2 };
		Gson gson = new Gson();
		String json = gson.toJson(arr);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().print(json.toString());

		// return arr;
	}

	@RequestMapping("/deleteProduct.action")
	public void deleteProduct(HttpServletResponse response, Integer id) throws IOException, MyException {
		PrintWriter out = response.getWriter();
		// System.out.println(id);
		int i = ps.removeProductByid(id);
		if (i != 0) {
			out.print("删除成功!!!");
		} else {
			out.print("删除失败!!!");
		}
	}
	
	
	//默认是and  可以改成or
	@RequiresPermissions(value= {"prduct:select","product:all"},logical=Logical.OR)
	@RequestMapping("/product_select.action")
	public String productSearch(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			Model model) throws IOException, MyException {
		return "admin/product/productSearch.jsp";
	}

	// 需要的权限

	@RequestMapping("/addProduct.action")
	public void addproduct(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model)
			throws IOException, MyException {
		String product_name = request.getParameter("product_name");
		Double income_price = Double.parseDouble(request.getParameter("income_price"));
		int proId = Integer.parseInt(request.getParameter("pro"));
		int quantity = Integer.parseInt(request.getParameter("quantity"));
		Double sales_price = Double.parseDouble(request.getParameter("sales_price"));
		int cateId = Integer.parseInt(request.getParameter("cate"));
		PrintWriter out = response.getWriter();
		Products p = new Products(product_name, income_price, new Providers(proId), quantity, sales_price,
				new Categorys(cateId));
		System.err.println(p);
		int i = ps.addProduct(p);
		if (i != 0) {
			out.write("<script>alert('添加成功！');location.href='productSearch.action'</script>");
		} else {
			out.write("<script>alert('添加失败！');location.href='productSearch.action'</script>");
		}
	}

	@RequiresPermissions("product:update")
	@RequestMapping("/readyEdit.action")
	public @ResponseBody Products readyEdit(HttpServletResponse response, Integer pid) throws IOException {
		Products p = ps.findProductById(pid);
		/*
		 * JSONArray json = JSONArray.fromObject(p);
		 * response.getWriter().print(json.toString());
		 */
		return p;
	}

	@RequestMapping("/product_insert.action")
	public ModelAndView addProduct(HttpServletResponse response, Integer pid) throws IOException {
		ModelAndView mav = new ModelAndView();
		List<Providers> list1 = pros.findAllProvider();
		List<Categorys> list2 = cs.findAllCategory();
		mav.addObject("list1", list1);
		mav.addObject("list2", list2);
		mav.setViewName("admin/product/addProduct.jsp");
		return mav;
	}
	
	@RequiresPermissions("product:update")
	@RequestMapping("/doEdit.action")
	public void doEdit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int productID = Integer.parseInt(request.getParameter("productID"));
		String product_name = request.getParameter("product_name");
		Double income_price = Double.parseDouble(request.getParameter("income_price"));
		int proId = Integer.parseInt(request.getParameter("pro"));
		int quantity = Integer.parseInt(request.getParameter("quantity"));
		Double sales_price = Double.parseDouble(request.getParameter("sales_price"));
		int cateId = Integer.parseInt(request.getParameter("cate"));
		String income_time = request.getParameter("income_time");
		PrintWriter out = response.getWriter();
		Products p = new Products(productID, product_name, income_price, new Providers(proId), quantity, sales_price,
				new Categorys(cateId), income_time);

		int i = ps.modifyProductById(p);
		if (i != 0) {
			out.print("<script>alert('修改成功！');location.href='productSearch.action'</script>");
		} else {
			out.print("<script>alert('修改失败！');location.href='productSearch.action'</script>");
		}
	}

	@RequestMapping(value = "/SearchByPage.action")
	public void doSearchByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String product_name = request.getParameter("product_name");
		int providerID = Integer.parseInt(request.getParameter("providerID"));
		int categoryID = Integer.parseInt(request.getParameter("categoryID"));

		int offset = Integer.parseInt(request.getParameter("offset")); // bootstrap算好的传过来的忽略数0
		int pageSize = Integer.parseInt(request.getParameter("limit"));
		int currentPage = offset / pageSize + 1;
		// 开始分页
		PageHelper.startPage(currentPage, pageSize);
		// 请求数据库之前
		Products p1 = new Products(product_name, new Providers(providerID), new Categorys(categoryID));
		System.err.println(p1 + "=================================");
		// 执行数据库操作
		List<Products> list = ps.findAllProductByPageCondition(p1);

		PageInfo<Products> page = new PageInfo<Products>(list);

		BootStrapPage<Products> bootPage = new BootStrapPage<Products>();
		// 使用bootstrap插件分页需要符合其数据格式
		bootPage.setTotal(page.getTotal());
		bootPage.setRows(list);
		Gson gson = new Gson();
		String json = gson.toJson(bootPage);
		response.getWriter().print(json.toString());
		// response.getWriter().print(json.toString());
	}

}
